package com.ruicar.afs.cloud.afscase.loanapprove.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.CaseApproveRecord;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPool;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.autoaudit.service.IRuleAtomDataService;
import com.ruicar.afs.cloud.afscase.backtopartnersinfo.entity.CaseBackToPartnersInfo;
import com.ruicar.afs.cloud.afscase.backtopartnersinfo.service.CaseBackToPartnersInfoService;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelAffiliatedUnits;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelRiskInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelWitnessInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelAffiliatedUnitsService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelWitnessInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.*;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.afscase.loanactivatepool.service.LoanActivateService;
import com.ruicar.afs.cloud.afscase.loanapprove.condition.InvoiceOcrCondition;
import com.ruicar.afs.cloud.afscase.loanapprove.condition.LoanApproveCondition;
import com.ruicar.afs.cloud.afscase.loanapprove.condition.LoanBackReasonCondition;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.*;
import com.ruicar.afs.cloud.afscase.loanapprove.service.*;
import com.ruicar.afs.cloud.afscase.loanapprove.task.condition.CarInsuranceInfoCondition;
import com.ruicar.afs.cloud.afscase.loanapprove.vo.*;
import com.ruicar.afs.cloud.afscase.loandealerfirstmortgage.entity.LoanDealerFirstMortgage;
import com.ruicar.afs.cloud.afscase.loandealerfirstmortgage.service.LoanDealerFirstMortgageService;
import com.ruicar.afs.cloud.afscase.loanmoderuleinfo.entity.LoanModeRuleInfo;
import com.ruicar.afs.cloud.afscase.loanmoderuleinfo.service.LoanModeRuleInfoService;
import com.ruicar.afs.cloud.afscase.loansecondaryfraudinfo.entity.LoanSecondaryFraudInfo;
import com.ruicar.afs.cloud.afscase.loansecondaryfraudinfo.service.LoanSecondaryFraudInfoService;
import com.ruicar.afs.cloud.afscase.loanspecialbusinessinfo.entity.LoanSpecialBusinessInfo;
import com.ruicar.afs.cloud.afscase.loanspecialbusinessinfo.service.LoanSpecialBusinessInfoService;
import com.ruicar.afs.cloud.afscase.loansuspendrule.entity.LoanSuspendRule;
import com.ruicar.afs.cloud.afscase.loansuspendrule.service.LoanSuspendRuleService;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.afscase.mq.entity.CaseMqAcceptRecord;
import com.ruicar.afs.cloud.afscase.mq.entity.CaseMqCompareInfo;
import com.ruicar.afs.cloud.afscase.mq.service.CaseMqAcceptRecordService;
import com.ruicar.afs.cloud.afscase.mq.service.CaseMqCompareInfoService;
import com.ruicar.afs.cloud.afscase.processor.enums.LoanSubmitEnum;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.rules.service.AfsRuleInfoService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.security.service.AfsUser;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.common.rules.RuleHelper;
import com.ruicar.afs.cloud.common.rules.constants.RuleRunEnum;
import com.ruicar.afs.cloud.common.rules.dto.RuleRunResult;
import com.ruicar.afs.cloud.invoice.config.InvoiceTokenProperties;
import com.ruicar.afs.cloud.invoice.dto.InvoiceCheckDto;
import com.ruicar.afs.cloud.invoice.feign.InvoiceApiFeign;
import com.ruicar.afs.cloud.parameter.commom.enums.InsuranceTypeEnums;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.core.date.DateUnit.DAY;

/**
 * @author yk.Li
 * @Date 2020/7/27
 * @description
 */
@Service
@AllArgsConstructor
@Data
@Slf4j
public class LoanApproveServiceImpl implements LoanApproveService {
    /**
     * 二次反欺诈
     */
    private final LoanSecondaryFraudInfoService loanSecondaryFraudInfoService;
    /**
     * 贷中特殊业务申请
     */
    private final LoanSpecialBusinessInfoService loanSpecialBusinessInfoService;
    /**
     * 退件记录
     */
    private final CaseBackToPartnersInfoService caseBackToPartnersInfoService;
    /**
     * 基本信息
     */
    private final CaseBaseInfoService caseBaseInfoService;
    /**
     * 合同信息
     */
    private CaseContractInfoService caseContractInfoService;
    /**
     * 渠道与申请件关联信息
     */
    private final CaseChannelInfoService caseChannelInfoService;
    /**
     * 渠道信息
     */
    private final ChannelBaseInfoService channelBaseInfoService;
    /**
     * 渠道见证人
     */
    private final ChannelWitnessInfoService channelWitnessInfoService;
    /**
     * 客户信息
     */
    private final CaseCustInfoService caseCustInfoService;
    /**
     * 车辆信息
     */
    private final CaseCarInfoService caseCarInfoService;
    /**
     * 渠道挂靠信息
     */
    private final ChannelAffiliatedUnitsService channelAffiliatedUnitsService;
    /**
     * 费用信息
     */
    private final CaseCostInfoService caseCostInfoService;
    /**
     * 费用信息  --车款
     */
    private final CaseFinancingItemsService caseFinancingItemsService;
    /**
     * 增容项
     */
    private final AddedFinancingItemsService addedFinancingItemsService;
    /**
     * 保险信息
     */
    private final CarInsuranceInfoService carInsuranceInfoService;
    /**
     * 发票信息
     */
    private final CarInvoiceInfoService carInvoiceInfoService;
    /**
     * 还款信息（银行卡申请信息）
     */
    private final LoanBankCardInfoService loanBankCardInfoService;
    /**
     * 工作流
     */
    private final LoanWorkflowService loanWorkflowService;
    /**
     * MQ通知
     */
    private final ApproveLoanInfoService approveLoanInfoService;
    /**
     * 放款待激活池
     */
    private final LoanActivateService loanActivateService;

    /**
     * 规则报文组装
     */
    private IRuleAtomDataService ruleAtomDataService;

    /**优先级历史记录*/
    private CasePriorityRecordService casePriorityRecordService;

    /**审批记录*/
    private CaseApproveRecordService caseApproveRecordService;

    private InvoiceTokenProperties invoiceTokenProperties;

    private InvoiceApiFeign invoiceApiFeign;

    private WorkTaskPoolService workTaskPoolService;

    private CaseMqCompareInfoService caseMqCompareInfoService;

    private AfsRuleInfoService afsRuleInfoService;

    private LoanModeRuleInfoService loanModeRuleInfoService;

    private LoanDealerFirstMortgageService loanDealerFirstMortgageService;

    private ChannelRiskInfoService channelRiskInfoService;

    private LoanSuspendRuleService loanSuspendRuleService;

    private CaseCustHistoryService caseCustHistoryService;

    private CasePriorityChangeService casePriorityChangeService;

    private CaseMqAcceptRecordService caseMqAcceptRecordService;
    /**
     * 通过申请编号获取二次反欺诈信息
     *
     * @param condition
     * @return
     */
    @Override
    public List<LoanSecondaryFraudInfo> getSecondaryFraudInfoList(LoanApproveCondition condition) {
        log.info("*****************二次反欺诈信息【" + isNull(condition.getApplyNo()) + "】**************");
        List<LoanSecondaryFraudInfo> info = loanSecondaryFraudInfoService.list(Wrappers.<LoanSecondaryFraudInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), LoanSecondaryFraudInfo::getApplyNo, condition.getApplyNo()));
        return info;
    }

    /**
     * 通过合同号获取贷中特殊业务申请
     *
     * @param condition
     * @return
     */
    @Override
    public List<LoanSpecialBusinessInfo> getSpecialBusinessInfoList(LoanApproveCondition condition) {
        log.info("*****************贷中特殊业务申请【" + isNull(condition.getApplyNo()) + "】**************");
        List<LoanSpecialBusinessInfo> info = loanSpecialBusinessInfoService.list(Wrappers.<LoanSpecialBusinessInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getContractNo()), LoanSpecialBusinessInfo::getContractNo, condition.getContractNo()));
        return info;
    }

    /**
     * 通过申请编号查询退件记录
     *
     * @param condition
     * @return
     */
    @Override
    public List<CaseBackToPartnersInfo> getBackToPartnersInfoList(LoanApproveCondition condition) {
        log.info("****************查询退件记录【" + isNull(condition.getContractNo()) + "】**************");
        List<CaseBackToPartnersInfo> info = caseBackToPartnersInfoService.list(Wrappers.<CaseBackToPartnersInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getContractNo()), CaseBackToPartnersInfo::getContractNo, condition.getContractNo()));
        return info;
    }

    @Override
    public List<CaseCustHistory> getCaseCustHistory(LoanApproveCondition condition) {
        log.info("****************查询客户身份证信息变更记录【" + isNull(condition.getApplyNo()) + "】**************");
        CaseCustInfo mainInCaseCustInfo = caseCustInfoService.getOne(Wrappers.<CaseCustInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()),CaseCustInfo::getApplyNo,condition.getApplyNo())
                .eq(CaseCustInfo::getCustRole,CustRoleEnum.MIANCUST.getCode()),false);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String mainInfoDate="";
        String joinInfoDate="";
        String histroyDate="";
        CaseCustInfo joinInCaseCustInfo = caseCustInfoService.getOne(Wrappers.<CaseCustInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()),CaseCustInfo::getApplyNo,condition.getApplyNo())
                .eq(CaseCustInfo::getCustRole,CustRoleEnum.COMMONCSUT.getCode()),false);
        List<CaseCustHistory> caseCustHistories = caseCustHistoryService.list(Wrappers.<CaseCustHistory>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()),CaseCustHistory::getApplyNo,condition.getApplyNo()));
        if(!CollectionUtils.isEmpty(caseCustHistories)){
            for(int i=0;i<caseCustHistories.size();i++){
                histroyDate=sdf.format(caseCustHistories.get(i).getCertEndDate());
                if(!ObjectUtils.isEmpty(mainInCaseCustInfo)){
                    mainInfoDate=sdf.format(mainInCaseCustInfo.getCertEndDate());
                    if(caseCustHistories.get(i).getCustRole().equals(CustRoleEnum.MIANCUST.getCode()) && histroyDate.equals(mainInfoDate)){
                        caseCustHistories.remove(caseCustHistories.get(i));
                    }
                }
                if(!ObjectUtils.isEmpty(joinInCaseCustInfo)){
                    joinInfoDate=sdf.format(joinInCaseCustInfo.getCertEndDate());
                    if(caseCustHistories.get(i).getCustRole().equals(CustRoleEnum.COMMONCSUT.getCode()) &&
                            histroyDate.equals(joinInfoDate)){
                        caseCustHistories.remove(caseCustHistories.get(i));
                    }
                }
            }
        }
        return caseCustHistories;
    }

    /**
     * 通过申请编号查询基本信息
     *
     * @param condition
     * @return
     */
    @Override
    public CaseBaseInfo getCaseBaseInfoList(LoanApproveCondition condition) {
        log.info("*****************查询案件基本信息【" + isNull(condition.getApplyNo()) + "】**************");
        CaseBaseInfo info = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CaseBaseInfo::getApplyNo, condition.getApplyNo()), false);
        return info;
    }

    /**
     * 通过申请编号查询合同信息
     *
     * @param condition
     * @return
     */
    @Override
    public CaseContractInfo getCaseContractInfoList(LoanApproveCondition condition) {
        log.info("*****************查询合同基本信息【" + isNull(condition.getApplyNo()) + "】**************");
        CaseContractInfo info = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CaseContractInfo::getApplyNo, condition.getApplyNo()), false);
        return info;
    }

    /**
     * 通过申请编号查询渠道基础信息
     *
     * @param condition
     * @return
     */
    @Override
    public ChannelBaseInfo getChannelBaseInfoList(LoanApproveCondition condition) {
        CaseChannelInfo caseChannelInfo = getCaseChannelInfo(isNull(condition.getApplyNo()));
        if (null != caseChannelInfo) {
            log.info("*****************查询渠道基本信息【" + isNull(condition.getApplyNo()) + "】*****************");
            ChannelBaseInfo info = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
                    .eq(StringUtils.isNotEmpty(caseChannelInfo.getDealerNo()), ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()), false);
            return info;
        }
        return null;
    }


    /**
     * 通过申请编号查询渠道见证人信息
     * 放款审核页面使用合同表中绑定的见证人信息
     *
     * @param condition
     * @return
     */
    @Override
    public ChannelWitnessInfo getChannelWitnessInfoList(LoanApproveCondition condition) {
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CaseContractInfo::getContractNo, condition.getContractNo()), false);
        if (null != caseContractInfo&&StringUtils.isNotBlank(caseContractInfo.getWitnessId())) {
            log.info("*****************查询渠道见证人信息【" + isNull(condition.getApplyNo()) + "】*****************");
            ChannelWitnessInfo info = channelWitnessInfoService.getOne(Wrappers.<ChannelWitnessInfo>query().lambda()
                    .eq(ChannelWitnessInfo::getWitnessIdCard, caseContractInfo.getWitnessId()),false);
            return info;
        }
        return new ChannelWitnessInfo();
    }

    /**
     * 获取渠道评分信息
     *
     * @param condition
     * @return
     */
    @Override
    public ChannelRiskInfo getChannelRiskInfo(LoanApproveCondition condition) {
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CaseContractInfo::getApplyNo, condition.getApplyNo()), false);
        if (null != caseContractInfo) {
            CaseChannelInfo caseChannelInfo=caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>lambdaQuery().eq(CaseChannelInfo::getApplyNo,caseContractInfo.getApplyNo()));
            log.info("*****************查询渠道评分信息【" + isNull(condition.getApplyNo()) + "】*****************");
            ChannelBaseInfo channelBaseInfo=channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>lambdaQuery().eq(ChannelBaseInfo::getChannelCode,caseChannelInfo.getDealerNo()));
            if(null != channelBaseInfo){
                ChannelRiskInfo channelRiskInfo = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfo>query().lambda()
                    .eq(ChannelRiskInfo::getChannelId,channelBaseInfo.getChannelId())
                        .eq(ChannelRiskInfo::getBusinessType,caseContractInfo.getBusinessType()));
                return channelRiskInfo;
            }
        }
        return null;
    }

    /**
     * 通过申请编号查询客户信息
     *
     * @param condition
     * @return
     */
    @Override
    public List<CaseCustInfo> getCaseCustInfoList(LoanApproveCondition condition) {
        log.info("*****************查询客户主借人信息【" + isNull(condition.getApplyNo()) + "】*****************");
        List<CaseCustInfo> infoList = caseCustInfoService.list(Wrappers.<CaseCustInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CaseCustInfo::getApplyNo, condition.getApplyNo()));
        log.info("*****************end:查询客户主借人信息【" + isNull(condition.getApplyNo()) + "】*****************");
        /**查找变更值*/
        infoList.forEach(info->{
            List<CaseMqCompareInfo> caseMqCompareInfos= caseMqCompareInfoService.list(Wrappers.<CaseMqCompareInfo>lambdaQuery()
                    .eq(CaseMqCompareInfo::getDataId,info.getId().toString())
                    .orderByDesc(CaseMqCompareInfo::getCreateTime));
            if(!CollectionUtils.isEmpty(caseMqCompareInfos)){
                Map map = JSON.parseObject(caseMqCompareInfos.get(0).getDifferentData(), HashMap.class);
                info.setChangeMap(map);
            }
        });
        return infoList;
    }

    /**
     * 通过申请编号查询车辆信息
     *
     * @param condition
     * @return
     */
    @Override
    public CaseCarInfo getCaseCarInfoList(LoanApproveCondition condition) {
        log.info("*****************查询车辆信息【" + isNull(condition.getContractNo()) + "】*****************");
        CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getContractNo()), CaseCarInfo::getContractNo, condition.getContractNo()), false);
        List dataIdList = new ArrayList();
        List<CaseMqCompareInfo> caseMqCompareInfoList = caseMqCompareInfoService.list(Wrappers.<CaseMqCompareInfo>query().lambda()
                .eq(CaseMqCompareInfo::getContractNo,condition.getContractNo())
                .ne(CaseMqCompareInfo::getDataId,"null"));
        if(!CollectionUtils.isEmpty(caseMqCompareInfoList)){
            Map resultMap = new HashMap();
            caseMqCompareInfoList.forEach(caseMqCompareInfo -> {
                Map paramsMap = JSON.parseObject(caseMqCompareInfo.getDifferentData(), HashMap.class);
                Iterator it = paramsMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    Object key = entry.getKey();
                    resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");
                }
            });
            caseCarInfo.setChangeMap(resultMap);
        }
        return caseCarInfo;
    }

    /**
     * 通过申请编号查询渠道挂靠信息
     *
     * @param condition
     * @return
     */
    @Override
    public ChannelAffiliatedUnits getChannelAffiliatedUnitsList(LoanApproveCondition condition) {
        CaseCarInfo caseCarInfo = getCaseCarInfoList(condition);
        if (null != caseCarInfo) {
            ChannelAffiliatedUnits info = new ChannelAffiliatedUnits();
            if (StringUtils.isNotEmpty(caseCarInfo.getAffCompanyId())) {
                log.info("*****************查询渠道挂靠信息【" + isNull(condition.getApplyNo()) + "】*****************");
                info = channelAffiliatedUnitsService.getOne(Wrappers.<ChannelAffiliatedUnits>query().lambda()
                        .eq(ChannelAffiliatedUnits::getId, Long.parseLong(caseCarInfo.getAffCompanyId())), false);
            } else {
                log.info("*****************查询个体工商挂靠信息【" + isNull(condition.getApplyNo()) + "】*****************");
                info.setAffiliatedName(caseCarInfo.getIndBusinessName());
                info.setSocUniCrtCode(caseCarInfo.getIndBusinessUsci());
            }
            return info;
        }
        return null;
    }

    /**
     * 通过申请编号查询保险信息
     *
     * @param condition
     * @return
     */
    @Override
    public CarInsuranceInfoVO getCarInsuranceInfoList(LoanApproveCondition condition) {
        log.info("*****************查询纸质保险信息【" + isNull(condition.getApplyNo()) + "】*****************");
        List<CarInsuranceInfo> insuranceInfoList = carInsuranceInfoService.list(Wrappers.<CarInsuranceInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CarInsuranceInfo::getApplyNo, condition.getApplyNo()));

        CarInsuranceInfoVO insuranceInfoVO = new CarInsuranceInfoVO();
        for (CarInsuranceInfo info : insuranceInfoList) {
            insuranceInfoVO.setInsuranceMode(info.getInsuranceMode());
            insuranceInfoVO.setInsuranceStartTime(info.getInsuranceStartTime());
            insuranceInfoVO.setInsuranceEndTime(info.getInsuranceEndTime());
        }
        return insuranceInfoVO;
    }

    /**
     * @param
     * @Description 通过申请编号查询电子保费信息
     * @Author yk.Li
     * @Date 2020/08/21
     */
    @Override
    public List<CarInsuranceInfoVO> getElectronicsInsuranceInfo(LoanApproveCondition condition) {
        log.info("*****************查询电子保单保险信息【" + isNull(condition.getApplyNo()) + "】*****************");
        List<CarInsuranceInfoVO> infoList = new ArrayList<>();
        List<CarInsuranceInfo> insuranceInfoList = carInsuranceInfoService.list(Wrappers.<CarInsuranceInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CarInsuranceInfo::getApplyNo, condition.getApplyNo()));
        CaseCustInfo custInfo = caseCustInfoService.getOne(Wrappers.<CaseCustInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), CaseCustInfo::getApplyNo, condition.getApplyNo())
                .eq(CaseCustInfo::getCustRole, CustRoleEnum.MIANCUST.getCode()), false);
        FinFinancingItems itemsInfo = caseFinancingItemsService.getOne(Wrappers.<FinFinancingItems>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), FinFinancingItems::getApplyNo, condition.getApplyNo())
                .eq(FinFinancingItems::getFinanceItemCode, "F002"));
        CaseCarInfo carInfo = getCaseCarInfoList(condition);
        CaseContractInfo contractInfo = getCaseContractInfoList(condition);
        CarInsuranceInfoVO insuranceInfoVO = new CarInsuranceInfoVO();
        if(!CollectionUtils.isEmpty(insuranceInfoList)){
            for (CarInsuranceInfo info : insuranceInfoList) {
                insuranceInfoVO.setInsuranceCompany(info.getInsuranceCompany());
                insuranceInfoVO.setInsuranceMode(info.getInsuranceMode());
                //车架号是否一致
                insuranceInfoVO.setCarVin(info.getCarVin()==null?"":info.getCarVin().equals(carInfo.getCarVin()) ? "一致" : "不一致");
                if (ObjectUtil.isNotNull(info.getPurpose()) && !"".equals(info.getPurpose())) {
                    insuranceInfoVO.setPurpose(AfsEnumUtil.desc(AfsEnumUtil.getEnum(info.getPurpose(), CarFunctionEnum.class)));
                }
                insuranceInfoVO.setInsuranceStartTime(info.getInsuranceStartTime());
                insuranceInfoVO.setInsuranceEndTime(info.getInsuranceEndTime());
                //计算保险是否有效
                if (null != info.getInsuranceEndTime() && null != contractInfo.getLendingFirstDate()) {
                    Date lendingFirstDateAddNine = DateUtil.offsetMonth(contractInfo.getLendingFirstDate(), 9);
                    insuranceInfoVO.setIsExpirationDate(between(info.getInsuranceEndTime(), lendingFirstDateAddNine) ? "是" : "否");
                }
                if (InsuranceTypeEnums.BUSINESS.getCode().equals(info.getInsuranceType())) {
                    //商业险被保险人是否一致
                    insuranceInfoVO.setBusinessName(info.getInsuranceCustName()==null?"":info.getInsuranceCustName().equals(custInfo.getCustName()) ? "一致" : "不一致");
                    insuranceInfoVO.setBusinessAmt(info.getInsuranceAmt());
                } else if (InsuranceTypeEnums.COMPULSORY.getCode().equals(info.getInsuranceType())) {
                    //交强险险人是否一致
                    insuranceInfoVO.setCompulsoryName(info.getInsuranceCustName()==null?"":info.getInsuranceCustName().equals(custInfo.getCustName()) ? "一致" : "不一致");
                    insuranceInfoVO.setCompulsoryCustNo(info.getInsuranceCustNo()==null?"":info.getInsuranceCustNo().equals(custInfo.getCertNo()) ? "一致" : "不一致");
                    insuranceInfoVO.setCompulsoryAmt(info.getInsuranceAmt());
                } else if (InsuranceTypeEnums.VEHICLE_LOSS.getCode().equals(info.getInsuranceType())) {
                    insuranceInfoVO.setVehicleLossAmt(info.getInsuranceAmt());
                } else if (InsuranceTypeEnums.THEFT.getCode().equals(info.getInsuranceType())) {
                    insuranceInfoVO.setTheftAmt(info.getInsuranceAmt());
                } else if (InsuranceTypeEnums.THIRD_PARTY.getCode().equals(info.getInsuranceType())) {
                    insuranceInfoVO.setThirdPartyAmt(info.getInsuranceAmt());
                } else if (InsuranceTypeEnums.VEHICLE_VESSEL_TAX.getCode().equals(info.getInsuranceType())) {
                    insuranceInfoVO.setVehicleVesselTaxAmt(info.getInsuranceAmt());
                }
            }
            //交强险合计
            insuranceInfoVO.setCompulsoryTotal((null != insuranceInfoVO.getCompulsoryAmt() ? insuranceInfoVO.getCompulsoryAmt() : BigDecimal.ZERO)
                    .add(null != insuranceInfoVO.getVehicleVesselTaxAmt() ? insuranceInfoVO.getVehicleVesselTaxAmt() : BigDecimal.ZERO));
            //总合计费用
            insuranceInfoVO.setTotal((null != insuranceInfoVO.getCompulsoryTotal() ? insuranceInfoVO.getCompulsoryTotal() : BigDecimal.ZERO)
                    .add(null != insuranceInfoVO.getBusinessAmt() ? insuranceInfoVO.getBusinessAmt() : BigDecimal.ZERO));
            if(!ObjectUtils.isEmpty(itemsInfo)){
                insuranceInfoVO.setPremiumIsMeet(insuranceInfoVO.getTotal()
                        .compareTo(null != itemsInfo.getFinanceItemAmt() ? itemsInfo.getFinanceItemAmt() : BigDecimal.ZERO) == -1 ? "不满足" : "满足");
            }
            infoList.add(insuranceInfoVO);
        }


        return infoList;
    }

    /**
     * @param startDate
     * @param endDate
     * @Description 判断startDate是否小于endDate
     * @Author yk.Li
     * @Date 2020/08/21
     */
    public Boolean between(Date startDate, Date endDate) {
        Long day = DateUtil.between(startDate,endDate,DAY,false);
        return day>0;
    }


    /**
     * 通过申请编号查询费用信息
     *
     * @param condition
     * @return
     */
    @Override
    public List<FinCostDetails> getCaseCostInfoList(LoanApproveCondition condition) {
        log.info("*****************查询费用信息【" + isNull(condition.getApplyNo()) + "】*****************");
        List<FinCostDetails> info = caseCostInfoService.list(Wrappers.<FinCostDetails>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), FinCostDetails::getApplyNo, condition.getApplyNo()));
        return info;
    }

    /**
     * 通过申请编号查询总费用信息
     *
     * @param condition
     * @return
     */
    @Override
    public CaseCostInfoVO getCostTotalInfo(LoanApproveCondition condition) {
        log.info("*****************查询费用总信息【" + isNull(condition.getApplyNo()) + "】*****************");
        return caseCostInfoService.costTotal(condition.getApplyNo());
    }

    /**
     * 通过合同号查询发票信息
     *
     * @param condition
     * @return
     */
    @Override
    public CarInvoiceInfo getCarInvoiceInfo(LoanApproveCondition condition) {
        log.info("*****************发票信息【" + isNull(condition.getContractNo()) + "】*****************");
        CarInvoiceInfo info = carInvoiceInfoService.getOne(Wrappers.<CarInvoiceInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getContractNo()), CarInvoiceInfo::getContractNo, condition.getContractNo()));
        return info;
    }

    /**
     * 通过申请编号查询融资项目信息
     * 表结构搞成这样我也是服了 表设计是真的******#¥%&%¥#¥%&
     * @param condition
     * @return
     */
    @Override
    public List<FinFinancingItemsVO> getCaseFinancingItemsList(LoanApproveCondition condition) {
        log.info("*****************通过申请编号查询融资项目信息【" + isNull(condition.getApplyNo()) + "】*****************");
        List<String> itemCodes = new ArrayList<>();
        itemCodes.add("F001");//购置税

        //融资金额  排除-购置税-
        List<FinFinancingItems> itemsList = caseFinancingItemsService.list(Wrappers.<FinFinancingItems>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), FinFinancingItems::getApplyNo, condition.getApplyNo())
        .notIn(FinFinancingItems::getFinanceItemCode,itemCodes));

        //实际成交价格
        List<AddedFinancingItems>  addItemsList = addedFinancingItemsService.list(Wrappers.<AddedFinancingItems>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), AddedFinancingItems::getApplyNo, condition.getApplyNo()));
        //取出父节点所有数据
        List<FinFinancingItems> isParentList = itemsList.stream().filter(item->null==item.getUpperId()).collect(Collectors.toList());
        List<AddedFinancingItems> addIsParentList = addItemsList.stream().filter(item->null==item.getUpperId()).collect(Collectors.toList());

        //取出子节点所有数据
        List<FinFinancingItems> isSonList = itemsList.stream().filter(item->null!=item.getUpperId()).collect(Collectors.toList());
        List<AddedFinancingItems> addIsSonList = addItemsList.stream().filter(item->null!=item.getUpperId()).collect(Collectors.toList());

        //组装附加项目'融资金额'
        List<FinFinancingItemsVO> itemsVOS = new ArrayList<>();
        for(FinFinancingItems items:isParentList){
            FinFinancingItemsVO vo = new FinFinancingItemsVO();
            vo.setFinanceItemName(items.getFinanceItemName());
            vo.setFinanceItemAmt(items.getFinanceItemAmt());

            //添加实际成交价格
            for(AddedFinancingItems addItem : addIsParentList){
                if(items.getId().equals(addItem.getUpperId())){
                    vo.setRealFinanceItemAmt(addItem.getAddFinanceAmt());
                }
            }
            if(ObjectUtil.isNull(vo.getRealFinanceItemAmt())){
                vo.setRealFinanceItemAmt(vo.getFinanceItemAmt());
            }
            //组装增融项
            BigDecimal realFinanceItemAmt = BigDecimal.ZERO;
            List<FinFinancingItemsVO> children = new ArrayList<>();
            for(FinFinancingItems sonItems:isSonList){
                //组装当前父节点项目包含的子项目
                if(items.getId().equals(sonItems.getUpperId())){
                    FinFinancingItemsVO sonVo = new FinFinancingItemsVO();
                    sonVo.setFinanceItemName(sonItems.getFinanceItemName());
                    sonVo.setFinanceItemAmt(sonItems.getFinanceItemAmt());

                    //添加实际成交价格
                    for(AddedFinancingItems addItem : addIsSonList){
                        if(items.getId().equals(addItem.getUpperId())){
                            sonVo.setRealFinanceItemAmt(addItem.getAddFinanceAmt());
                        }
                    }
                    if(ObjectUtil.isNull(vo.getRealFinanceItemAmt())){
                        vo.setRealFinanceItemAmt(vo.getFinanceItemAmt());
                    }
                    children.add(sonVo);
                }
            }
            vo.setChildren(children);
            itemsVOS.add(vo);
        }

        return itemsVOS;
    }

    /**
     * 获取首单抵押详情
     * @Author rongji.zhang
     * @param
     * @return
     */
    @Override
    public Boolean getIsFirstMortgage(LoanApproveCondition condition){

        List<CaseCarInfo> caseCarInfoList = caseCarInfoService.list(Wrappers.<CaseCarInfo>query().lambda()
                    .eq(CaseCarInfo::getApplyNo, condition.getApplyNo()));
        Boolean result = true;
        if (!CollectionUtils.isEmpty(caseCarInfoList)) {
            CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                    .eq(CaseChannelInfo::getApplyNo, caseCarInfoList.get(0).getApplyNo()));
            log.info("合同{}:首单抵押规则执行开始...",condition.getApplyNo());
            List<LoanModeRuleInfo> afsRuleInfoList = loanModeRuleInfoService.list(Wrappers.<LoanModeRuleInfo>query().lambda()
                    .eq(LoanModeRuleInfo::getIsEnable,WhetherEnum.YES.getCode()));
            if(!CollectionUtils.isEmpty(afsRuleInfoList)){
                List<String> list=afsRuleInfoList.stream().map(loanModeRuleInfo->loanModeRuleInfo.getId().toString()).collect(Collectors.toList());
                JSONObject runParam=ruleAtomDataService.getCommonAtomRunParams(condition.getApplyNo());
                RuleRunResult ruleResult = RuleHelper.runRule(runParam,list,false,RuleRunEnum.SERIAL );
                if (ruleResult.getHit()) {
                    List<String> lendingModeList = loanModeRuleInfoService.list(Wrappers.<LoanModeRuleInfo>query().lambda()
                            .in(LoanModeRuleInfo::getId,list)).stream().map(s->s.getLendingMode()).collect(Collectors.toList());
                    int j=0;
                    for(int i=0;i<lendingModeList.size();i++){
                        if(lendingModeList.get(i).equals(LendingModeEnum.CHANNEL.getCode())){
                            List<LoanDealerFirstMortgage> loanDealerFirstMortgage = loanDealerFirstMortgageService.list(Wrappers.<LoanDealerFirstMortgage>query().lambda()
                                    .eq(LoanDealerFirstMortgage::getDealerNo,caseChannelInfo.getDealerNo())
                                    .eq(LoanDealerFirstMortgage::getIsFirstMortgage, WhetherEnum.YES.getCode()));
                            if (CollectionUtils.isEmpty(loanDealerFirstMortgage)) {
                                j++;
                            }
                        }
                        if(lendingModeList.get(i).equals(LendingModeEnum.CHANNEL_AND_PROVINCE.getCode())){
                            List<LoanDealerFirstMortgage> loanDealerFirstMortgage = loanDealerFirstMortgageService.list(Wrappers.<LoanDealerFirstMortgage>query().lambda()
                                    .eq(LoanDealerFirstMortgage::getDealerNo,caseChannelInfo.getDealerNo())
                                    .eq(LoanDealerFirstMortgage::getIsFirstMortgage, WhetherEnum.YES.getCode())
                                    .in(LoanDealerFirstMortgage::getProvinceCode, caseCarInfoList.stream().map(s->s.getPurchaseProvince()).collect(Collectors.toList())));
                            if (CollectionUtils.isEmpty(loanDealerFirstMortgage)) {
                                j++;
                            }
                        }
                        if(lendingModeList.get(i).equals(LendingModeEnum.CHANNEL_PROVINCE_CITY.getCode())){
                            List<LoanDealerFirstMortgage> loanDealerFirstMortgage = loanDealerFirstMortgageService.list(Wrappers.<LoanDealerFirstMortgage>query().lambda()
                                    .eq(LoanDealerFirstMortgage::getDealerNo, caseChannelInfo.getDealerNo())
                                    .eq(LoanDealerFirstMortgage::getIsFirstMortgage, WhetherEnum.YES.getCode())
                                    .in(LoanDealerFirstMortgage::getProvinceCode, caseCarInfoList.stream().map(s->s.getPurchaseProvince()).collect(Collectors.toList()))
                                    .in(LoanDealerFirstMortgage::getCityCode, caseCarInfoList.stream().map(s->s.getPurchaseCity()).collect(Collectors.toList())));
                            if (CollectionUtils.isEmpty(loanDealerFirstMortgage)) {
                                j++;
                            }
                        }
                    }
                    if(j>0){
                        result = false;
                    }
                }
                log.info("合同{}:首单抵押规则执行结束...",condition.getApplyNo());
            } else {
                log.info("合同{}:首单抵押规则执行结束...",condition.getApplyNo());
            }
        } else {
            log.info("合同{}:首单抵押规则执行结束...",condition.getApplyNo());
        }
        return result;
    }

    /**
     * 通过申请编号查询融资项目信息
     * 表结构搞成这样我也是服了 表设计是真的******#¥%&%¥#¥%&
     * @param condition
     * @return
     */
    @Override
    public List<FinFinancingItemsVO> getCaseAddFinancingItemsList(LoanApproveCondition condition) {
        log.info("*****************通过申请编号查询融资项目信息【" + isNull(condition.getApplyNo()) + "】*****************");

        List<FinFinancingItemsVO> financingItemsList=new ArrayList<>();
        //实际成交价格
        List<AddedFinancingItems>  addItemsList = addedFinancingItemsService.list(Wrappers.<AddedFinancingItems>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), AddedFinancingItems::getApplyNo, condition.getApplyNo())
                .eq(AddedFinancingItems::getDelFlag,"0"));
        Map<Long, AddedFinancingItems> addMap = addItemsList.stream().collect(Collectors.toMap(AddedFinancingItems::getId, f -> f));


        if(!CollectionUtils.isEmpty(addItemsList)){
            addItemsList.forEach(addedFinancingItems -> {
                FinFinancingItemsVO finFinancingItemsVO = new FinFinancingItemsVO();
                FinFinancingItems finFinancingItems = caseFinancingItemsService.getOne(Wrappers.<FinFinancingItems>lambdaQuery()
                        .eq(FinFinancingItems::getApplyNo, addedFinancingItems.getApplyNo())
                        .eq(FinFinancingItems::getFinanceItemCode,addedFinancingItems.getFinanceItemCode()));
                BeanUtils.copyProperties(finFinancingItems, finFinancingItemsVO);
                finFinancingItemsVO.setRealFinanceItemAmt(addedFinancingItems.getAddFinanceAmt());
                finFinancingItemsVO.checkStatus();
                financingItemsList.add(finFinancingItemsVO);
            });

            Map<Long, FinFinancingItemsVO> voMap = financingItemsList.stream().collect(Collectors.toMap(FinFinancingItemsVO::getId, f -> f));
            List<FinFinancingItemsVO> childrenList = financingItemsList.stream().filter(item -> null != item.getUpperId()).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(childrenList)) {
                Map<Long, List<FinFinancingItemsVO>> childrenMap = childrenList.stream().collect(Collectors.groupingBy(FinFinancingItemsVO::getUpperId));
                if (voMap.size() > 0) {
                    childrenMap.forEach((key, value) -> {
                        FinFinancingItemsVO financingItemsVO = voMap.get(key);
                        for(FinFinancingItemsVO vo:value){
                            if(!vo.isQualified()){
                                financingItemsVO.setQualified(false);
                            }
                        }
                        financingItemsVO.setChildren(value);
                        financingItemsList.removeAll(value);
                    });
                }
            }
        }
        return financingItemsList;
    }

    /**
     * 通过申请编号查询融资项目信息
     * 表结构搞成这样我也是服了 表设计是真的******#¥%&%¥#¥%& :)同意
     * @param condition
     * @return
     */
    @Override
    public List<AddedFinancingItemsVO> getAddFinancingItemsList(LoanApproveCondition condition) {
        log.info("*****************通过申请编号查询融资项目信息【" + isNull(condition.getApplyNo()) + "】*****************");

        List<AddedFinancingItemsVO> financingItemsList=new ArrayList<>();
        /**查询未显示的融资项目*/
        List<FinFinancingItems>  finFinancingItemsList = caseFinancingItemsService.list(Wrappers.<FinFinancingItems>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), FinFinancingItems::getApplyNo, condition.getApplyNo())
                .isNull(FinFinancingItems::getIsView).ne(FinFinancingItems::getFinanceItemAmt,BigDecimal.ZERO));
        if(!CollectionUtils.isEmpty(finFinancingItemsList)){
            finFinancingItemsList.forEach(finFinancingItems -> {
                AddedFinancingItemsVO addedItemsVO=new AddedFinancingItemsVO();
                addedItemsVO.setId(finFinancingItems.getId());
                addedItemsVO.setApplyFinanceItemAmt(finFinancingItems.getFinanceItemAmt());
                addedItemsVO.setFinanceItemName(finFinancingItems.getFinanceItemName());
                addedItemsVO.setFinanceItemCode(finFinancingItems.getFinanceItemCode());
                addedItemsVO.setQualified(false);
                financingItemsList.add(addedItemsVO);
            });
        }
        //实际成交价格
        List<AddedFinancingItems>  addItemsList = addedFinancingItemsService.list(Wrappers.<AddedFinancingItems>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), AddedFinancingItems::getApplyNo, condition.getApplyNo())
                .eq(AddedFinancingItems::getDelFlag,"0"));
        addItemsList.forEach(addedFinancingItems -> {
            AddedFinancingItemsVO addedFinancingItemsVO=new AddedFinancingItemsVO();
            BeanUtils.copyProperties(addedFinancingItems, addedFinancingItemsVO);
            FinFinancingItems finFinancingItems = caseFinancingItemsService.getOne(Wrappers.<FinFinancingItems>lambdaQuery()
                    .eq(FinFinancingItems::getApplyNo, addedFinancingItems.getApplyNo())
                    .eq(FinFinancingItems::getFinanceItemCode,addedFinancingItems.getFinanceItemCode()));
            if(!ObjectUtils.isEmpty(finFinancingItems)){
                addedFinancingItemsVO.setApplyFinanceItemAmt(finFinancingItems.getFinanceItemAmt());
                addedFinancingItemsVO.checkStatus();
            }
            financingItemsList.add(addedFinancingItemsVO);
        });
        Map<Long, AddedFinancingItemsVO> voMap = financingItemsList.stream().collect(Collectors.toMap(AddedFinancingItemsVO::getId, f -> f));
        List<AddedFinancingItemsVO> childrenList = financingItemsList.stream().filter(item -> null != item.getUpperId()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(childrenList)) {
            Map<Long, List<AddedFinancingItemsVO>> childrenMap = childrenList.stream().collect(Collectors.groupingBy(AddedFinancingItemsVO::getUpperId));
            if (voMap.size() > 0) {
                childrenMap.forEach((key, value) -> {
                    AddedFinancingItemsVO financingItemsVO = voMap.get(key);
                    for(AddedFinancingItemsVO vo:value){
                        if(!vo.isQualified()){
                            financingItemsVO.setQualified(false);
                        }
                    }
                    financingItemsVO.setChildren(value);
                    financingItemsList.removeAll(value);
                });
            }
        }
        return financingItemsList;
    }
    /**
     * 通过申请编号查询客户银行信息
     *
     * @param condition
     * @return
     */
    @Override
    public LoanBankCardInfo getLoanBankCardInfoList(LoanApproveCondition condition) {
        log.info("*****************客户银行信息【" + isNull(condition.getApplyNo()) + "】*****************");
        LoanBankCardInfo info = loanBankCardInfoService.getOne(Wrappers.<LoanBankCardInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getApplyNo()), LoanBankCardInfo::getApplyNo, condition.getApplyNo()), false);
            List<CaseMqCompareInfo> caseMqCompareInfos= caseMqCompareInfoService.list(Wrappers.<CaseMqCompareInfo>lambdaQuery()
                    .eq(CaseMqCompareInfo::getDataId,info.getId().toString())
                    .orderByDesc(CaseMqCompareInfo::getCreateTime));
            if(!CollectionUtils.isEmpty(caseMqCompareInfos)){
                Map map = JSON.parseObject(caseMqCompareInfos.get(0).getDifferentData(), HashMap.class);
                info.setChangeMap(map);
            }
        return info;
    }

    /**
     * 获取渠道关联申请件信息
     *
     * @param applyNo
     * @return
     */
    private CaseChannelInfo getCaseChannelInfo(String applyNo) {
        return caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                .eq(StringUtils.isNotEmpty(applyNo), CaseChannelInfo::getApplyNo, applyNo));
    }

    /**
     * 判空
     *
     * @param str
     * @return
     */
    private String isNull(String str) {
        return StringUtils.isNotEmpty(str) ? str : null;
    }

    @Transactional
    @Override
    public void auditSubmit(LoanApproveCondition condition) {
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(StringUtils.isNotBlank(condition.getContractNo()), CaseContractInfo::getContractNo, condition.getContractNo()));
        /**初审提交至复审，案件优先级大于等于5，统一变成5，小于5则不变*/
        int priorityValue=Integer.valueOf(caseContractInfo.getPriority());
        if(priorityValue>=Integer.valueOf(PriorityEnum.ORDINARY.getCode())){
            caseContractInfoService.update(Wrappers.<CaseContractInfo>lambdaUpdate()
                    .eq(StringUtils.isNotBlank(condition.getContractNo()), CaseContractInfo::getContractNo, condition.getContractNo())
                    .set(CaseContractInfo::getPriority, PriorityEnum.ORDINARY.getCode()));
        }
        //修改放款审核状态
        caseContractInfoService.updateApplyStatus(condition.getContractNo(), ApplyStatusEnum.LOAN_WAIT_CONFIRM.getState());
        log.info("*****************" + condition.getContractNo() + "放款审核状态change:" + ApplyStatusEnum.LOAN_WAIT_CONFIRM.getState() + "*****************");

        //工作流提交流程  保存操作记录
        condition.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        condition.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
        condition.setApproveSuggest(AfsEnumUtil.key(LoanSubmitEnum.SUBMIT));
        condition.setFlowNode(FlowNodeEnum.PRIMARY.getCode());
        loanWorkflowService.submitWorkflow(condition);
        caseContractInfoService.updateLoanAuditor(condition.getContractNo(), SecurityUtils.getUsername());
        caseContractInfoService.update(Wrappers.<CaseContractInfo>lambdaUpdate()
                .eq(StringUtils.isNotEmpty(condition.getContractNo()), CaseContractInfo::getContractNo, condition.getContractNo())
                .set(CaseContractInfo::getFlowNode, FlowNodeEnum.REVIEW.getCode()));
        /**复核规则*/
        this.setReviewFlag(condition.getContractNo());
        //通知进件系统
        approveLoanInfoService.sendToApplyNotic(condition.getContractNo()
                , ApplyStatusEnum.LOAN_WAIT_CONFIRM);
    }

    /**
     * @Description 保存首单抵押单号信息
     * @Author rongji.zhang
     * @Date 2020/09/28
     */
    @Override
    public void saveIsFirstMortgage(String contractNo) {
        try {
            CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                    .eq(CaseContractInfo::getContractNo, contractNo));
            if (!ObjectUtils.isEmpty(caseContractInfo)) {
                //获取合作商信息
                CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                        .eq(CaseChannelInfo::getApplyNo, caseContractInfo.getApplyNo()));
                ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
                        .eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
                //获取购车城市信息
                CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                        .eq(CaseCarInfo::getApplyNo, caseContractInfo.getApplyNo())
                        .eq(CaseCarInfo::getContractNo, caseContractInfo.getContractNo()));
                if (!ObjectUtils.isEmpty(caseCarInfo) && !ObjectUtils.isEmpty(channelBaseInfo)) {
                    LoanDealerFirstMortgage loanDealerFirstMortgage = loanDealerFirstMortgageService.getOne(Wrappers.<LoanDealerFirstMortgage>query().lambda()
                            .eq(LoanDealerFirstMortgage::getDealerNo, channelBaseInfo.getChannelCode())
                            .eq(LoanDealerFirstMortgage::getProvinceCode, caseCarInfo.getPurchaseProvince())
                            .eq(LoanDealerFirstMortgage::getCityCode, caseCarInfo.getPurchaseCity()));
                    if (!ObjectUtils.isEmpty(loanDealerFirstMortgage)) {
                        loanDealerFirstMortgage.setDealerNo(channelBaseInfo.getChannelCode());
                        loanDealerFirstMortgage.setDealerName(channelBaseInfo.getChannelFullName());
                        loanDealerFirstMortgage.setChannelType(channelBaseInfo.getChannelType());
                        loanDealerFirstMortgage.setIsFirstMortgage(WhetherEnum.YES.getCode());
                        loanDealerFirstMortgage.setProvinceCode(caseCarInfo.getPurchaseProvince());
                        loanDealerFirstMortgage.setCityCode(caseCarInfo.getPurchaseCity());
                        loanDealerFirstMortgage.setFirstCaseNo(caseContractInfo.getContractNo());
                        loanDealerFirstMortgageService.updateById(loanDealerFirstMortgage);
                    } else {
                        LoanDealerFirstMortgage loanDealerFirstMortgage1 = new LoanDealerFirstMortgage();
                        loanDealerFirstMortgage1.setDealerNo(channelBaseInfo.getChannelCode());
                        loanDealerFirstMortgage1.setDealerName(channelBaseInfo.getChannelFullName());
                        loanDealerFirstMortgage1.setChannelType(channelBaseInfo.getChannelType());
                        loanDealerFirstMortgage1.setIsFirstMortgage(WhetherEnum.YES.getCode());
                        loanDealerFirstMortgage1.setProvinceCode(caseCarInfo.getPurchaseProvince());
                        loanDealerFirstMortgage1.setCityCode(caseCarInfo.getPurchaseCity());
                        loanDealerFirstMortgage1.setFirstCaseNo(caseContractInfo.getContractNo());
                        loanDealerFirstMortgageService.save(loanDealerFirstMortgage1);
                    }
                }
            }
        }catch (Exception e){
            log.error("{}首单落库失败--",contractNo,e);
        }
    }

    /**
     * 获取OCR验证结果
     * @Author rongji.zhang
     * @Date 2020/8/12
     * @param invoiceOcrCondition
     * @return
     */
    @Override
    public InvoiceCheckVo getInvoiceCheck(InvoiceOcrCondition invoiceOcrCondition) throws Exception{
        InvoiceCheckDto invoiceCheckDto= new InvoiceCheckDto();
        invoiceCheckDto.setCode(invoiceOcrCondition.getMachinePrintedCode());
        invoiceCheckDto.setNumber(invoiceOcrCondition.getMachineNumber());
        invoiceCheckDto.setTime(invoiceOcrCondition.getBillingDatas());
        invoiceCheckDto.setTotal(invoiceOcrCondition.getTotalPriceTax());
        invoiceCheckDto.setVerifyNo("");
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type","application/json");
        headers.put("X-Auth-Token", invoiceTokenProperties.getToken());
        JSONObject invoiceCheck =invoiceApiFeign.InvoiceCheck(invoiceCheckDto,headers);
        InvoiceCheckVo invoiceCheckVo=new InvoiceCheckVo();
        invoiceCheckVo.setCode(invoiceCheck.getString("code"));
        invoiceCheckVo.setMessage(invoiceCheck.getString("message"));
        invoiceCheckVo.setAnalyzeId(invoiceCheck.getString("analyzeId"));
        invoiceCheckVo.setMachinePrintedCode(invoiceOcrCondition.getMachinePrintedCode());
        invoiceCheckVo.setMachineNumber(invoiceOcrCondition.getMachineNumber());
        invoiceCheckVo.setTotalPriceTax(invoiceOcrCondition.getTotalPriceTax());
        invoiceCheckVo.setBillingData(invoiceOcrCondition.getBillingDatas());
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        CarInvoiceInfo carInvoiceInfo=carInvoiceInfoService.getOne(Wrappers.<CarInvoiceInfo>query().lambda()
                .eq(CarInvoiceInfo::getContractNo,invoiceOcrCondition.getContractNo()));
        carInvoiceInfo.setInvoiceCode(invoiceOcrCondition.getMachinePrintedCode());
        carInvoiceInfo.setInvoiceNumber(invoiceOcrCondition.getMachineNumber());
        try {
            Date billinfDate = ft.parse(invoiceOcrCondition.getBillingDatas());
            carInvoiceInfo.setInvoiceDate(billinfDate);
            carInvoiceInfo.setInvoiceAmt(new BigDecimal(invoiceCheckDto.getTotal()));
        }catch (ParseException e){
            e.printStackTrace();
        }
        carInvoiceInfoService.updateById(carInvoiceInfo);
        invoiceCheckVo.setBillingData(invoiceOcrCondition.getBillingDatas());
        return invoiceCheckVo;
    }
    @Transactional
    @Override
    public void backToDealer(LoanApproveCondition condition) {
        //添加退回原因提交时间
        List<CaseBackToPartnersInfo> caseBackToPartnersInfoList = caseBackToPartnersInfoService.list(Wrappers.<CaseBackToPartnersInfo>query().lambda()
                .eq(CaseBackToPartnersInfo::getContractNo,condition.getContractNo()));
        if(!CollectionUtils.isEmpty(caseBackToPartnersInfoList)){
            caseBackToPartnersInfoList.forEach(caseBackToPartnersInfo -> {
                if(caseBackToPartnersInfo.getBackTime()==null){
                    caseBackToPartnersInfo.setBackTime(new Date());
                    caseBackToPartnersInfoService.updateById(caseBackToPartnersInfo);
                }
            });
        }
        //清楚合同表执行步骤
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                .eq(CaseContractInfo::getContractNo,condition.getContractNo()));
        //修改放款审核状态
        if(!ObjectUtils.isEmpty(caseContractInfo)){
            caseContractInfo.setWorkflowPrevStep(1);
            caseContractInfo.setFlowNode(FlowNodeEnum.CHANNEL.getCode());
            caseContractInfo.setApplyStatus(ApplyStatusEnum.LOAN_RETURN.getState());
            caseContractInfoService.updateById(caseContractInfo);
        }
        log.info("*****************" + condition.getContractNo() + " 放款审核状态change:" + ApplyStatusEnum.LOAN_RETURN.getState() + "*****************");

        //工作流提交流程  保存操作记录
        condition.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        condition.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
        condition.setApproveSuggest(AfsEnumUtil.key(LoanSubmitEnum.BACK_PARTNERS));
        condition.setFlowNode(FlowNodeEnum.PRIMARY.getCode());
        loanWorkflowService.submitWorkflow(condition);
    }

    @Transactional
    @Override
    public void reviewSubmit(LoanApproveCondition condition) {
        //修改放款审核状态
        caseContractInfoService.updateApplyStatus(condition.getContractNo(), ApplyStatusEnum.LOAN_PRE_APPROVE.getState());
        log.info("*****************" + condition.getApplyNo() + " 放款审核状态change:" + ApplyStatusEnum.LOAN_PRE_APPROVE.getState() + "*****************");
        //更新放款通过时间
        caseContractInfoService.update(Wrappers.<CaseContractInfo>lambdaUpdate()
                .eq(StringUtils.isNotEmpty(condition.getContractNo()), CaseContractInfo::getApplyNo, condition.getApplyNo())
                .set(CaseContractInfo::getLendingPassDate, new Date()).set(CaseContractInfo::getFlowNode, FlowNodeEnum.AUTO.getCode()));

        //复审完成  待激活池插入数据
        loanActivateService.addLoanActivateInfo(condition.getApplyNo());
        log.info("*****************复核完成待激活池插入待激活数据*****************");

        //工作流提交流程  保存操作记录
        condition.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        condition.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
        condition.setApproveSuggest(AfsEnumUtil.key(LoanSubmitEnum.SUBMIT));
        condition.setFlowNode(FlowNodeEnum.REVIEW.getCode());
        loanWorkflowService.submitWorkflow(condition);

        //通知进件系统
        approveLoanInfoService.sendToApplyNotic(condition.getContractNo(), ApplyStatusEnum.LOAN_PRE_APPROVE);
    }

    @Transactional
    @Override
    public void backToAudit(LoanApproveCondition condition) {
        //清除必复核标记
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                .eq(CaseContractInfo::getContractNo,condition.getContractNo()));
        caseContractInfo.setNeedReview(WhetherEnum.NO.getCode());
        caseContractInfoService.updateById(caseContractInfo);
        //修改放款审核状态
        caseContractInfoService.updateApplyStatus(condition.getContractNo(), ApplyStatusEnum.LOAN_REVIEW_RETURN.getState());
        log.info("*****************" + condition.getApplyNo() + "放款审核状态change:" + ApplyStatusEnum.LOAN_REVIEW_RETURN.getState() + "*****************");
        CaseContractInfo info=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo,condition.getContractNo()));
        info.setFlowNode(FlowNodeEnum.PRIMARY.getCode());
        caseContractInfoService.updateById(info);
        //工作流提交流程  保存操作记录
        condition.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        condition.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
        condition.setApproveSuggest(AfsEnumUtil.key(LoanSubmitEnum.BACK_AUDIT));
        condition.setFlowNode(FlowNodeEnum.REVIEW.getCode());
        loanWorkflowService.submitWorkflowByScheduleInfo(condition);

        //通知进件系统
        approveLoanInfoService.sendToApplyNotic(condition.getContractNo(), ApplyStatusEnum.LOAN_WAIT_APPROVE);
    }

    /**
     * 复核规则
     */
    @Override
    public void setReviewFlag(String contractNo) {
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                .eq(CaseContractInfo::getContractNo, contractNo));
        if (!ObjectUtils.isEmpty(caseContractInfo)) {
            JSONObject runParams = ruleAtomDataService.getCommonAtomRunParamsLoan(contractNo);
            log.info("{}复核规则报文：{}", contractNo, runParams);
            try {
                RuleRunResult result = RuleHelper.runRule(runParams, "reviewRuleGroup", false, RuleRunEnum.SERIAL);
                if (result.getHit()) {
                    caseContractInfo.setNeedReview(WhetherEnum.YES.getCode());
                    caseContractInfoService.updateById(caseContractInfo);
                } else {
                    log.info("合同号{}复核规则未命中！", contractNo);
                }
            } catch (Exception e) {
                log.error("合同号{}复核规则调用失败！{}", contractNo, e);
            }
        } else {
            log.error("复核规则：合同号{}未找到相应合同信息", contractNo);
        }
    }

    @Override
    public void savePaperInfo(CarInsuranceInfoCondition info) {
        List<CarInsuranceInfo> infoList = carInsuranceInfoService.list(Wrappers.<CarInsuranceInfo>lambdaQuery()
                .eq(StringUtils.isNoneBlank(info.getContractNo()), CarInsuranceInfo::getContractNo, info.getContractNo()));
        for(CarInsuranceInfo insuranceInfo:infoList){
            insuranceInfo.setInsuranceStartTime(info.getInsuranceStartTime());
            insuranceInfo.setInsuranceEndTime(info.getInsuranceEndTime());
            carInsuranceInfoService.saveOrUpdate(insuranceInfo);
        }
    }

    @Override
    public void lockContract(String contractNo,String remarks){
            CaseContractInfo caseContractInfo=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo,contractNo));
                caseContractInfo.setLockDegree(LockDegreeEnum.MEDIUM.getValue());
                caseContractInfo.setIsLock(WhetherEnum.YES.getCode());
                caseContractInfo.setPriority(casePriorityChangeService.priorityChange(caseContractInfo));
                caseContractInfo.setRemarks(remarks);
                caseContractInfoService.updateById(caseContractInfo);

//                CasePriorityRecord casePriorityRecord= new CasePriorityRecord();
//                casePriorityRecord.setApplyNo(caseContractInfo.getApplyNo());
//                casePriorityRecord.setContractNo(caseContractInfo.getContractNo());
//                casePriorityRecord.setPriority(PriorityEnum.LOWEST.getCode());
//                casePriorityRecord.setReason(PriorityReasonEnum.FRAUD.getCode());
//                casePriorityRecord.setBusiNode(AfsEnumUtil.key(StepSceneEnum.LOAN));
//                casePriorityRecordService.save(casePriorityRecord);
    }
    @Override
    public void unLockContract(String contractNo,String remarks){
        CaseContractInfo caseContractInfo=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo,contractNo));
//        List<CasePriorityRecord> records=casePriorityRecordService.list(Wrappers.<CasePriorityRecord>lambdaQuery()
//                .eq(CasePriorityRecord::getContractNo,contractNo).orderByDesc(CasePriorityRecord::getCreateTime));
//        String priority=PriorityEnum.ORDINARY.getCode();//默认优先级5
//        if(!CollectionUtils.isEmpty(records)&&records.size()>1) {
//            String hisPriority=records.get(1).getPriority();
//            //如果有历史优先级，恢复之前的优先级
//            if(!hisPriority.equals(PriorityEnum.LOWEST.getCode())){
//                priority=hisPriority;
//            }
//        }
        caseContractInfo.setLoanSuspendRuleId("");
        caseContractInfo.setLockDegree(LockDegreeEnum.NORMAL.getValue());
        caseContractInfo.setIsLock(WhetherEnum.NO.getCode());
        caseContractInfo.setPriority(casePriorityChangeService.priorityChange(caseContractInfo));
        caseContractInfo.setRemarks("");
        caseContractInfoService.updateById(caseContractInfo);
//        CasePriorityRecord casePriorityRecord = new CasePriorityRecord();
//        casePriorityRecord.setApplyNo(caseContractInfo.getApplyNo());
//        casePriorityRecord.setContractNo(caseContractInfo.getContractNo());
//        casePriorityRecord.setPriority(priority);
//        casePriorityRecord.setReason(PriorityReasonEnum.REMOVE_LOCK.getCode());
//        casePriorityRecord.setBusiNode(AfsEnumUtil.key(StepSceneEnum.LOAN));
//        casePriorityRecordService.save(casePriorityRecord);
    }

    /**
     * add by rongji.zhang
     * 暂停拦截
     */
    @Override
    public Boolean setSuspend(CaseContractInfo contractInfo) {
        log.info("合同{}:拦截暂停检测开始执行...", contractInfo.getContractNo());
        List<LoanSuspendRule> activeLoanSuspendRules = loanSuspendRuleService.list(Wrappers.<LoanSuspendRule>lambdaQuery().eq(LoanSuspendRule::getIsEnable,WhetherEnum.YES.getCode()));
        if(CollectionUtils.isEmpty(activeLoanSuspendRules)){
            log.info("合同{}:未找到已启用的拦截暂停规则，跳过执行", contractInfo.getContractNo());
            return true;
        }else {
            JSONObject runParam = ruleAtomDataService.getCommonAtomRunParamsLoan(contractInfo.getContractNo());
            log.info("合同{}:拦截暂停规则报文：{}", contractInfo.getContractNo(), runParam);
            RuleRunResult result = RuleHelper.runRule(runParam, "suspendRuleGroup", false, RuleRunEnum.SERIAL);
            if (result.getHit()) {
                List listNo = result.getResults().stream().map(s -> {
                    return s.getRuleNo();
                }).collect(Collectors.toList());
                if (listNo.isEmpty()) {
                    log.info("未找到规则编号");
                    return true;
                } else {
                    log.info("命中规则编号：{}", listNo);
                    List<LoanSuspendRule> loanSuspendRules = loanSuspendRuleService.listByIds(listNo);
                    String lockReason = "";
                    for (int i = 0; i < loanSuspendRules.size(); i++) {
                        lockReason = lockReason + loanSuspendRules.get(i).getLockReason() + ";";
                    }
                    ;
                    if (!CollectionUtils.isEmpty(loanSuspendRules)) {
                        Optional<LoanSuspendRule> loanSuspendRule = loanSuspendRules.stream().max(Comparator.comparing(LoanSuspendRule::getLockDegree));
                        if (loanSuspendRule.get().getLockDegree().equals(LockDegreeEnum.HEIGHT.getValue())) {
                            //修改申请状态
                            caseBaseInfoService.update(Wrappers.<CaseBaseInfo>lambdaUpdate()
                                    .eq(CaseBaseInfo::getApplyNo, contractInfo.getApplyNo())
                                    .set(CaseBaseInfo::getBusinessStateIn, AfsEnumUtil.key(BusinessStateInEnum.REPEAL)));
                            //修改案件状态
                            contractInfo.setApplyStatus(ApplyStatusEnum.LOAN_DISCARD.getState());
                            contractInfo.setBusinessStage(BusinessStageEnum.LOAN_DISCARD.getCode());
                            contractInfo.setContractStatus(ContractStatusEnum.contractCancel);
                            caseContractInfoService.updateById(contractInfo);
                            //合同废弃记录
                            CaseApproveRecord lockOprRecord = new CaseApproveRecord();
                            String disposeStaff = "";
                            lockOprRecord.setContractNo(contractInfo.getContractNo());
                            lockOprRecord.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
                            AfsUser user = SecurityUtils.getUser();
                            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(user)) {
                                disposeStaff = user.getUserRealName();
                            } else {
                                disposeStaff = "暂停拦截";
                            }
                            lockOprRecord.setDisposeStaff(disposeStaff);
                            lockOprRecord.setApproveSuggest(ApplyStatusEnum.LOAN_DISCARD.getState());
                            lockOprRecord.setApproveSuggestName("合同取消");
                            lockOprRecord.setApproveStartTime(new Date());
                            lockOprRecord.setApproveEndTime(new Date());
                            lockOprRecord.setApproveType(ApproveTypeEnum.CANAEL.getValue());
                            lockOprRecord.setFlowNode(contractInfo.getFlowNode());
                            caseApproveRecordService.save(lockOprRecord);
                            //废弃信息通知进件系统
                            approveLoanInfoService.sendToApplyNotic(contractInfo.getContractNo(), ApplyStatusEnum.LOAN_DISCARD);
                            return false;
                        } else {
                            contractInfo.setLockDegree(loanSuspendRule.get().getLockDegree());
                            contractInfo.setIsLock(WhetherEnum.YES.getCode());
                            contractInfo.setIsTop(WhetherEnum.NO.getCode());
                            contractInfo.setPriority(casePriorityChangeService.priorityChange(contractInfo));
                            contractInfo.setRemarks(lockReason);
                            caseContractInfoService.updateById(contractInfo);
//                            CasePriorityRecord casePriorityRecord = new CasePriorityRecord();
//                            casePriorityRecord.setApplyNo(contractInfo.getApplyNo());
//                            casePriorityRecord.setContractNo(contractInfo.getContractNo());
//                            casePriorityRecord.setPriority(PriorityEnum.LOWEST.getCode());
//                            casePriorityRecord.setReason(PriorityReasonEnum.SUSPEND.getCode());
//                            casePriorityRecord.setBusiNode(AfsEnumUtil.key(StepSceneEnum.LOAN));
//                            casePriorityRecordService.save(casePriorityRecord);
                            return true;
                        }
                    } else {
                        return false;
                    }
                }
            } else {
                log.info("合同{}:拦截暂停规则未命中：{}", contractInfo.getContractNo(), result.getHit());
                return true;
            }
        }
    }

    @Override
    public void lockCase(String applyNo){
        List<CaseContractInfo> caseContractInfos=caseContractInfoService.list(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getApplyNo,applyNo));
        caseContractInfos.forEach(caseContractInfo->{
            caseContractInfo.setIsLock(WhetherEnum.YES.getCode());
            caseContractInfo.setPriority(casePriorityChangeService.priorityChange(caseContractInfo));
            caseContractInfo.setRemarks("疑似欺诈");
            caseContractInfoService.updateById(caseContractInfo);

//            CasePriorityRecord casePriorityRecord= new CasePriorityRecord();
//            casePriorityRecord.setApplyNo(caseContractInfo.getApplyNo());
//            casePriorityRecord.setContractNo(caseContractInfo.getContractNo());
//            casePriorityRecord.setPriority(PriorityEnum.LOWEST.getCode());
//            casePriorityRecord.setReason(PriorityReasonEnum.FRAUD.getCode());
//            casePriorityRecord.setBusiNode(AfsEnumUtil.key(StepSceneEnum.LOAN));
//            casePriorityRecordService.save(casePriorityRecord);
        });


    }

    @Override
    public void lockChannel(String channelCode){
        List<CaseChannelInfo> caseChannelInfos=caseChannelInfoService.list(Wrappers.<CaseChannelInfo>lambdaQuery().eq(CaseChannelInfo::getDealerNo,channelCode));
        caseChannelInfos.forEach(caseChannelInfo->{
            List<CaseContractInfo> caseContractInfos=caseContractInfoService.list(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getApplyNo,caseChannelInfo.getApplyNo()));
            caseContractInfos.forEach(caseContractInfo->{
                caseContractInfo.setIsLock(WhetherEnum.YES.getCode());
                caseContractInfo.setPriority(casePriorityChangeService.priorityChange(caseContractInfo));
                caseContractInfo.setRemarks("疑似欺诈");
                caseContractInfoService.updateById(caseContractInfo);

//                CasePriorityRecord casePriorityRecord= new CasePriorityRecord();
//                casePriorityRecord.setApplyNo(caseContractInfo.getApplyNo());
//                casePriorityRecord.setContractNo(caseContractInfo.getContractNo());
//                casePriorityRecord.setPriority(PriorityEnum.LOWEST.getCode());
//                casePriorityRecord.setReason(PriorityReasonEnum.FRAUD.getCode());
//                casePriorityRecord.setBusiNode(AfsEnumUtil.key(StepSceneEnum.LOAN));
//                casePriorityRecordService.save(casePriorityRecord);
            });
        });
    }

}
